// dialogDrag弹窗拖拽
import EventBus from '@/event-bus/EventBus.js';

const directive = {
  beforeMount(el, binding, vnode, oldVnode) {
    const dialogHeaderEl = el.querySelector('.title');
    if (!dialogHeaderEl) {
      // 如果弹窗组件隐藏了顶部栏，则不具备弹窗拖拽功能
      return;
    }
    const dragDom = el.querySelector('.winIndex');
    dialogHeaderEl.style.cursor = 'move';

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
    dialogHeaderEl.onmousedown = e => {
      // 鼠标按下，获取鼠标在盒子内的坐标
      const disX = e.clientX - dialogHeaderEl.offsetLeft;
      const disY = e.clientY - dialogHeaderEl.offsetTop;

      // 获取到的值带px 正则匹配替换
      let styL;
      let styT;

      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (sty.left.includes('%')) {
        styL = Number(document.body.clientWidth) * (Number(sty.left.replace(/\%/g, '')) / 100);
        styT = Number(document.body.clientHeight) * (Number(sty.top.replace(/\%/g, '')) / 100);
      } else {
        styL = Number(sty.left.replace(/px/g, ''));
        styT = Number(sty.top.replace(/px/g, ''));
      }

      // 鼠标移动的时候，把鼠标在页面中的坐标，减去鼠标在盒子内的坐标就是模态框的left和top值
      document.onmousemove = function(f) {
        // 通过事件委托，计算移动的距离 （开始拖拽至结束拖拽的距离）
        const l = f.clientX - disX;
        const t = f.clientY - disY;
        let finallyL = l + styL;
        let finallyT = t + styT; // 边界值判定 注意clientWidth scrollWidth区别 要减去之前的top left值

        const limitL = (document.documentElement.clientWidth - dragDom.offsetWidth);

        if (finallyL < 0) {
          finallyL = 0;
        } else if (finallyL > limitL) {
          finallyL = limitL;
        } else {
          finallyL = l + styL;
        }

        const limitT = document.documentElement.clientHeight * 15 / 100;
        const limitB = document.documentElement.clientHeight - dragDom.offsetHeight;

        if (finallyT < 0) {
          finallyT = 0;
        } else if (finallyT > limitB) {
          finallyT = limitB;
        } else {
          finallyT = t + styT;
        } // 移动当前元素

        dragDom.style.left = ''.concat(finallyL, 'px');
        dragDom.style.top = ''.concat(finallyT, 'px');
        const [winContainerWid] = dragDom.classList;
        EventBus.$emit('visual-win-container-move', winContainerWid);
      };

      document.onmouseup = function(ele) {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  },
};

if (!window.visualComp.directives.dialogDrag) {
  window.visualComp.directives.push('dialogDrag');
  window.xVueWeb.app.directive('dialogDrag', directive);
}
